package com.creative.accountsdk.holder;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.creative.accountsdk.AccountActivity;

import com.creative.accountsdk.AccountSdk;
import com.creative.accountsdk.Area;
import com.creative.accountsdk.DataCenter;
import com.creative.accountsdk.DialogUtils;

import com.creative.accountsdk.OnLoginListener;
import com.creative.accountsdk.R;
import com.creative.accountsdk.UserData;
import com.creative.accountsdk.UserInfor;
import com.creative.accountsdk.net.XHttpHandler;

import com.creative.accountsdk.net.account.ChildUnbindParentProtocol;
import com.creative.accountsdk.net.account.ParentUnbindChildProtocol;
import com.creative.accountsdk.net.account.UserInfoProtocol;
import com.creative.accountsdk.widget.AvatarView;
import com.creative.util.DataUtil;
import com.creative.util.DeviceUtils;
import com.creative.util.FileUtils;
import com.creative.util.JsonFileUtils;
import com.upyun.block.api.exception.UpYunException;
import com.upyun.block.api.listener.CompleteListener;
import com.upyun.block.api.main.UploaderManager;
import com.upyun.block.api.utils.UpYunUtils;
import com.widget.time.JudgeDate;
import com.widget.time.ScreenInfo;
import com.widget.time.WheelMain;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wang_qian on 2015/11/23.
 */
public class UserInfoHolder extends BaseHolder {

    private RadioButton rdoBtnGirl;
    private RadioButton rdoBtnBoy;
    private EditText edtTxtNickName;
    private EditText edtTxtBirthDay;
    private EditText edtTxtArea;
    private AvatarView ivAvatar;
    private Button btnOk;
    private TextView txtHint;
    private ListView lsArea;
    private TextView txtUnbind;

    private CountrylistAdapter m_lsadapter;
    private List<Area> areas;
    private Area       aresSelected = null;


    private UserInfor  userInfor;
    private String     tokingStr = null;

    private boolean    mHaveAvatar = false;
    private Uri cropUri;

    private String  fileName;
    private String  localFilePath;
    private  String  ypFilePath="";

    boolean  ifChn =false;
    private String selectTimeStr;

    boolean toModifyChildInfo = false;





    public UserInfoHolder(Activity  context) {
        super();
        activity = (AccountActivity)context;
        userInfor = UserData.getInstance().getUserinfor();
    }

    public UserInfoHolder(Activity  context, UserInfor userinfo, String toking) {
        super();
        activity = (AccountActivity)context;
        userInfor = userinfo;
        tokingStr = toking;
        toModifyChildInfo = true;
    }


    @Override
    protected void initViews() {

        rdoBtnBoy = (RadioButton)viewRoot.findViewById(R.id.boyRadioBtn);
        rdoBtnGirl = (RadioButton)viewRoot.findViewById(R.id.girlRadioBtn);
        edtTxtNickName = (EditText)viewRoot.findViewById(R.id.nicknameEditText);
        edtTxtBirthDay = (EditText)viewRoot.findViewById(R.id.birthdayEditText);
        edtTxtArea = (EditText)viewRoot.findViewById(R.id.areaEditText);
        ivAvatar = (AvatarView)viewRoot.findViewById(R.id.iv_register_round);
        btnOk = (Button)viewRoot.findViewById(R.id.finishBtn);
        txtHint = (TextView)viewRoot.findViewById(R.id.hintTextView);
        lsArea = (ListView)viewRoot.findViewById(R.id.ls_countrys);
        txtUnbind =(TextView)viewRoot.findViewById(R.id.tvunbind);

        setListensers();
        prepareData();

    }

    private void prepareData() {
        ifChn = DeviceUtils.isZh(activity);
        selectTimeStr = DeviceUtils.getCurrentYYYYmmForm();
        Gdx.init(activity);


        if (userInfor != null) {
            if (userInfor.gender == 1) {
                rdoBtnGirl.setChecked(true);
                ivAvatar.setImageResource(R.drawable.regsetting_img_girl);
            } else {
                rdoBtnBoy.setChecked(true);
                ivAvatar.setImageResource(R.drawable.regsetting_img_boy);
            }

            edtTxtNickName.setText(userInfor.nickname);

            if (!TextUtils.isEmpty(userInfor.birthday)) {
                selectTimeStr = userInfor.birthday;
                String time = selectTimeStr;
                if (ifChn) {
                    try {
                        time = DataUtil.getCurrentTime(selectTimeStr);
                    } catch (ParseException e) {
                        time="";
                    }
                }
                edtTxtBirthDay.setText(time);
            }



            if(!"".equals(userInfor.avatar) && null!=userInfor.avatar){
                String ypFilePath = Constants.upaiHost + userInfor.avatar;
                mHaveAvatar = true;
                ivAvatar.setAvatarUrl(ypFilePath);

            }

            if (userInfor.role == 2) {
                txtHint.setVisibility(View.VISIBLE);
            }

            initAreaList();
            if (areas != null && areas.size() > 0) {
                m_lsadapter = new CountrylistAdapter(activity);
                int area_num = areas.size();
                for (int i = 0; i < area_num; i++) {
                    if (userInfor.area.equals(areas.get(i).getAreaCode())) {
                        edtTxtArea.setText(getcountryname(areas.get(i)));
                        aresSelected = areas.get(i);
                        break;
                    }
                }
                lsArea.setAdapter(m_lsadapter);
                edtTxtArea.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        lsArea.scrollTo(0,0);
                        lsArea.setVisibility(View.VISIBLE);
                    }
                });
            }

            if (toModifyChildInfo) {
                txtUnbind.setVisibility(View.VISIBLE);
            }

        }
    }

    private void setListensers() {
        rdoBtnBoy.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if (!rdoBtnBoy.isChecked()) {
                    rdoBtnBoy.setChecked(true);
                    if (!mHaveAvatar) {
                        ivAvatar.setImageResource(R.drawable.regsetting_img_boy);
                    }
                }
            }
        });

        rdoBtnGirl.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if (!rdoBtnGirl.isChecked()) {
                    rdoBtnGirl.setChecked(true);
                    if (!mHaveAvatar) {
                        ivAvatar.setImageResource(R.drawable.regsetting_img_girl);
                    }
                }
            }
        });

        ivAvatar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                cropUri = Uri.fromFile(getCropFileHandle().file());
                popHeadDialog();

            }
        });

        edtTxtBirthDay.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                selectTime();
            }
        });

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyInfo();
            }
        });


        txtUnbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(txtUnbind);
            }
        });
    }

    @Override
    public int getLayoutResID() {
        if (DeviceUtils.isPad(activity)) {
            return R.layout.info_layout;
        } else {
            return R.layout.info_layout_phone;
        }
    }


    private void popHeadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.title_set_head);
        builder.setPositiveButton(R.string.button_take_picture, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                takePicture();
            }
        });
        builder.setNegativeButton(R.string.button_choose_picture, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                choosePicture();
            }
        });
        builder.create().show();
    }

    /**
     * 拍照
     */
    private void takePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(FileUtils.getCapture().file());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        activity.startActivityForResult(intent, Constants.REQUEST_TAKE_PICTURE);
    }

    /**
     * 选择照片
     */
    private void choosePicture() {
        //Intent.ACTION_PICK，这个得到的图片随后可以crop；Intent.ACTION_GET_CONTENT得到的图片无法直接crop，会提示图片无法加载
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setType("image/*");
        activity.startActivityForResult(intent, Constants.REQUEST_CHOOSE_PICTURE);
    }

    private FileHandle getCropFileHandle() {
        getFileName();
        localFilePath = Constants.ms_sp_wawayayareader+ File.separator+fileName;
        ypFilePath = File.separator+Constants.avatar+ File.separator+fileName;
        return FileUtils.getFileHandle(localFilePath);
    }

    private void  getFileName(){
        Date current = new Date();
        java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yy_MM_dd_HH_mm_ss");
        fileName=sdf.format(current)+"head.jpg";
    }

    public void chooseCropPicture(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,cropUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        activity.startActivityForResult(intent, Constants.REQUEST_CHOOSE_CROP_PICTURE);
    }

    public void cropPicture() {
        Uri uri = Uri.fromFile(FileUtils.getCapture().file());
        Intent intent = new Intent("com.android.camera.action.CROP");
        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        activity.startActivityForResult(intent, Constants.REQUEST_TAKE_CROP_PICTURE);
    }

    /**
     * 上传头像
     * @param localFilePath
     */
    private void  uploadPic(String  localFilePath){
        try {
            getCropFileHandle();
            File localFile = new File(localFilePath);
            UploaderManager uploaderManager = UploaderManager.getInstance(Constants.bucket);
            uploaderManager.setConnectTimeout(60);
            uploaderManager.setResponseTimeout(60);
            Map<String, Object> paramsMap = null;
            paramsMap = uploaderManager.fetchFileInfoDictionaryWith(localFile, ypFilePath);
            String policyForInitial = UpYunUtils.getPolicy(paramsMap);
            String signatureForInitial = UpYunUtils.getSignature(paramsMap, Constants.formApiSecret);
           // Log.e(TAG,"policyForInitial:"+policyForInitial+" signatureForInitial: "+signatureForInitial+"   localFile:"+localFile);
            uploaderManager.upload(policyForInitial, signatureForInitial, localFile, null, new MyCompleteListener());

        } catch (UpYunException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    class  MyCompleteListener implements CompleteListener {
        @Override
        public void result(boolean isComplete, String result, String error) {

            //pbLoading.setVisibility(View.GONE);
            //tvHeadImag.setVisibility(View.GONE);
            if (isComplete) {
                try {
                    JSONObject json =new JSONObject(result);
                    String path =   Constants.upaiHost+json.optString("path");
                    ivAvatar.setAvatarUrl(path);
                    userInfor.setAvatar("/avatar/"+fileName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setTakePicture() {
        String  localpath = Uri.fromFile(FileUtils.getCapture().file()).getPath();
        //ifCheckPic = true;

        //pbLoading.setVisibility(View.VISIBLE);
        //tvHeadImag.setVisibility(View.VISIBLE);
        uploadPic(localpath);
    }

    public void setChoosePicture(Uri uri) {
        String  localpath = "";
        if (uri != null) {
            localpath = uri.getEncodedPath();
        }
        if (TextUtils.isEmpty(localpath)) {
            localpath = cropUri.getPath();
        }
        if (!TextUtils.isEmpty(localpath)) {
           // ifCheckPic = true;
           // pbLoading.setVisibility(View.VISIBLE);
           // tvHeadImag.setVisibility(View.VISIBLE);
            uploadPic(localpath);
        }

    }


    WheelMain wheelMain;
    DateFormat dateFormat;
    String  formatTimeStr="yyyy年MM月dd日";
    View timepickerview ;
    int year ;
    int month ;
    int day ;
    private void  initSelectTime(){
        if(ifChn){
            formatTimeStr="yyyy年MM月dd日";
        }
        dateFormat= new SimpleDateFormat(formatTimeStr);
        LayoutInflater inflater=LayoutInflater.from(activity);
        timepickerview=inflater.inflate(R.layout.timepicker, null);
        ScreenInfo screenInfo = new ScreenInfo(activity);
        wheelMain = new WheelMain(timepickerview);
        wheelMain.screenheight = screenInfo.getHeight();
        String time = edtTxtBirthDay.getText().toString();
        Calendar calendar = Calendar.getInstance();
        if(JudgeDate.isDate(time, formatTimeStr)){
            try {
                calendar.setTime(dateFormat.parse(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    private void  selectTime(){
        initSelectTime();
        wheelMain.initDateTimePicker(year,month,day, !ifChn);
        new AlertDialog.Builder(activity)
                .setTitle(R.string.select_time_title)
                .setView(timepickerview)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        edtTxtBirthDay.setText(wheelMain.getTime(activity, !ifChn));
                        selectTimeStr = wheelMain.getTimeCont();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    private void modifyInfo()
    {
        int gender = 0;
        if (rdoBtnGirl.isChecked()) gender = 1;
        String birthday = selectTimeStr;
        String area = userInfor.area;
        if (aresSelected != null) {
            area = aresSelected.getAreaCode();
        }
        String nickname = userInfor.nickname;
        if (!TextUtils.isEmpty(userInfor.nickname)){
            nickname = edtTxtNickName.getEditableText().toString();
        }

        progress = DialogUtils.createProgress(activity);
        progress.show();
        String token = tokingStr;
        if (TextUtils.isEmpty(token)) {
            token = UserData.getInstance().getToken();
        }
         final UserInfoProtocol protocol = new UserInfoProtocol(gender,birthday,area, nickname, userInfor.getAvatar(), userInfor.uid, token);
        protocol.debugUrl(DataCenter.getHttpClient());



        DataCenter.getHttpClient().post(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity, progress) {
            @Override
            public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                progress.cancel();
                if (protocol.parse(response, activity)) {
                    if (!toModifyChildInfo) {
                        UserData.getInstance().initUserInfo(protocol.jsonUser);
                        UserData.getInstance().writeUserInfo(activity, protocol.jsonUser);
                    }
                    activity.finish();
                }
            }
        });


    }

    class CountrylistAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;

        public CountrylistAdapter(Context context) {
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public int getCount() {
            return areas.size();
        }

        @Override
        public Object getItem(int position) {
            try{
                return areas.get(position);
            }catch(Exception e){
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            GroupHolder groupHolder = null;
            final int ipos = position;
            final Area area  = areas.get(position);
            if (convertView == null) {
                groupHolder = new GroupHolder();
                convertView = inflater.inflate(R.layout.countrysimpletext, null);
                groupHolder.textView = (TextView) convertView.findViewById(R.id.tv_countryname);
                groupHolder.textView.setTextSize(15);
                groupHolder.textView.setTag(ipos);
                convertView.setTag(groupHolder);
            } else {
                groupHolder = (GroupHolder) convertView.getTag();
                groupHolder.textView.setTag(ipos);
            }
            groupHolder.textView.setText(getcountryname(area));

            groupHolder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != v) {

                        aresSelected = area;
                        edtTxtArea.setText(getcountryname(area));
                        lsArea.setVisibility(View.GONE);
                    }
                }

            });

            return convertView;
        }
    }

    private String getcountryname(final Area area){

        try{
            if(!ifChn) {
                return area.getAreaNameEN();
            }
            else{
                return area.getAreaNameCN();
            }

        }catch(Exception e){
        }
        return null;
    }


    class GroupHolder {
        TextView textView;
    }

    private void initAreaList() {
        JSONArray  areaArray = JsonFileUtils.json(activity);
        if (areaArray != null && areaArray.length() > 0) {
            areas = new ArrayList<Area>();
            int area_number = areaArray.length();
            for (int i = 0; i < area_number; i++) {
                try {
                    JSONObject jo = areaArray.getJSONObject(i);
                    Area area = new Area();
                    area.setAreaCode(jo.getString("country_code"));
                    area.setAreaNameCN(jo.getString("store_name_cn"));
                    area.setAreaNameEN(jo.getString("store_name_en"));
                    areas.add(area);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void showPopupWindow(View view) {


        View contentView = activity.getLayoutInflater().from(activity).inflate(
                R.layout.unbind_popup_layout, null);

        Button unbindbutton = (Button) contentView.findViewById(R.id.btnunbind);
        unbindbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                unbindChild();
            }
        });

        Button cancelBtn = (Button)contentView.findViewById(R.id.btncancel);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });

        final PopupWindow popupWindow = new PopupWindow(contentView,
                (int)activity.getResources().getDimension(R.dimen.unbind_popwindow_width),
                (int)activity.getResources().getDimension(R.dimen.unbind_popwindow_height), true);

        popupWindow.setTouchable(true);

        popupWindow.showAsDropDown(view);

    }

    private void unbindChild() {
        progress = DialogUtils.createProgress(activity);
        progress.show();
        final ParentUnbindChildProtocol protocol = new ParentUnbindChildProtocol(userInfor.uid);
        protocol.debugUrl(DataCenter.getHttpClient());
        DataCenter.getHttpClient().post(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity, progress) {
            @Override
            public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                progress.cancel();
                if (protocol.parse(response, activity)) {

                }
            }
        });


    }



}
